package com.geekstudy.week1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * 定义类加载器
 */
public class Week1HelloClassLoad extends ClassLoader{

    final String END_SUFFIX = ".xlass";

    /**
     * 重写 findClass方法
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected  Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classByte = readClassByte(name);
            if(classByte != null) {

                // 获取文件类名 目前简单支持获取 去最后/ 和 .xlass 之间的单词作为 Class Name
                String classEndName = name.substring(name.lastIndexOf("/") + 1, name.length());
                String className = classEndName.replace(END_SUFFIX, "");
                return defineClass(className, classByte, 0, classByte.length);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

    /**
     * 根据传入的filePath读取文件流 并将文件流做 255-x 操作
     * @param className
     * @return
     * @throws IOException
     */
    private byte[] readClassByte(String className) throws IOException {
        byte[] byteArray = null;
        if(className != null && className.endsWith(END_SUFFIX)) {
            File classFile = new File(className);
            if(classFile.exists()) {
                FileInputStream fileInputStream = new FileInputStream(classFile);
                if(fileInputStream != null) {
                    int available = fileInputStream.available();
                    byte[] readByte = new byte[available];
                    int readResult = fileInputStream.read(readByte);
                    System.out.println("Week1HelloClassLoad readResult:" + readResult + " available:" + available);
                    System.out.println("Week1HelloClassLoad array:" + Arrays.toString(readByte));

                    // 字节码转换 255 - bit 得到原始类文件流 不转换的异常
                    // Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 889275713 in class file Hello

                    byteArray = new byte[available];
                    for(int size = 0; size < available; size++) {
                        byteArray[size] = (byte)(255 - readByte[size]);
                    }
                    System.out.println("Week1HelloClassLoad decode:" + Arrays.toString(byteArray));

                }
            }

        }
        return byteArray;
    }
}
